package cn.youyeku.zsxh.ui.teacher;

/**
 * Created by youye on 17-4-17.
 */

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.youyeku.zsxh.R;
import cn.youyeku.zsxh.Utils.ConverUtils;
import cn.youyeku.zsxh.Utils.LogUtils;
import cn.youyeku.zsxh.Utils.NullUtils;
import cn.youyeku.zsxh.api.XhApi;
import cn.youyeku.zsxh.app;
import cn.youyeku.zsxh.bean.question_data;
import cn.youyeku.zsxh.bean.Question;
import cn.youyeku.zsxh.ui.activity.ABS.HandleActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static cn.youyeku.zsxh.common.Contanst.ALTER_NULL_INFO;


public class UpdateQuestions extends HandleActivity implements View.OnClickListener {


    /**
     * 题目
     */
    private EditText mQuestionDesc;
    private EditText mQuestionA;
    private EditText mQuestionB;
    private EditText mQuestionC;
    private EditText mQuestionD;
    /**
     * 回到上一题目
     */
    private Button mQuestionBackToFront;
    /**
     * 编写下一题目
     */
    private Button mQuestionToNext;
    /**
     * 提交数据
     */
    private Button mPostData;

    private String answer = "";
    private SparseArray<Question> all_data = new SparseArray<>();
    /**
     * A
     */

    private int curPage = 0;
    /**
     * A
     */
    private RadioButton mCheckA;
    /**
     * B
     */
    private RadioButton mCheckB;
    /**
     * C
     */
    private RadioButton mCheckC;
    /**
     * D
     */
    private RadioButton mCheckD;
    private RadioGroup mQuestionAnswerGroup;

    /**
     * 填写答案解析
     */
    private EditText mQuestionAnswerParse;
    private String data;
    private String question_post_id;
    private String question_post_test_name;
    private List<Question> questions = new ArrayList<>();

    @Override
    protected void onChange() {

    }

    @Override
    protected void onError() {

    }

    @Override
    protected void onSuccess() {

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_question_post);
        initView();
        initActionBar();

       question_data question_data = (question_data)getIntent().getSerializableExtra("data");
        question_post_id = question_data.getQuestion_id();
        question_post_test_name = question_data.getQuestion_desc();
//        //base64 转json ->List
        Gson gson = new Gson();

        questions = gson.fromJson(ConverUtils.Base64ToString(question_data.getQuestion_data()), new TypeToken<List<Question>>() {
        }.getType());
        setQuestData(questions.get(curPage));
        all_data=ConverUtils.ListToSparse(questions);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.question_back_to_front:
                LogUtils.w(curPage + " 保存现在修改" + all_data.size());
                if (curPage == all_data.size()) {
                    save_data_last();
                }
                int now = curPage - 1;
                if (now >= 0) {
                    LogUtils.w("获取" + now + "数据");
                    setQuestData(all_data.get(now));
                    curPage--;
                }
                break;
            case R.id.question_to_next:

                addquestion();
                break;
            case R.id.post_data:
                new MaterialDialog.Builder(this)
                        .title("输入随堂测试的试题名称")
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        //参数1：hint 参数2：自动填充的文字 参数3：监听
                        .input(null, question_post_test_name, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                if (!input.toString().equals("")) {
                                    question_post_test_name = input.toString();
                                    save_post_last();
                                }
                            }
                        }).show();

                break;
            case R.id.question_answer_group:
                break;
        }
    }

    private void save_post_last() {
        String desc = mQuestionDesc.getText().toString();
        String a = mQuestionA.getText().toString();
        String b = mQuestionB.getText().toString();
        String c = mQuestionC.getText().toString();
        String d = mQuestionD.getText().toString();
        String answerParse = mQuestionAnswerParse.getText().toString();

        if (NullUtils.isArrayNotNull(new String[]{desc, a, b, c, d, answer})) {


            all_data.append(curPage, new Question(desc, a, b, c, d, answer, answerParse));

            Gson g = new Gson();


            List<Question> questions;

            questions = ConverUtils.SparseToList(all_data);


            LogUtils.w(g.toJson(question_post_id+question_post_test_name+g.toJson(questions)));
            XhApi.post_question_update(question_post_id,question_post_test_name,g.toJson(questions), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        JSONObject object = new JSONObject(response.body().string());

                        String message = object.getString("message");
                        int code = object.getInt("code");
                        if (code == 200) {
                            finish();
                        }

                        app.backgroundThreadShortToast(message);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            });

//            Contanst.QUESTION_DATA = all_data;
            //转换成json提交

//            Intent intent = new Intent(getApplicationContext(), QuestionDoActivity.class);
//            startActivity(intent);
//            LogUtils.w("提交数据");

        } else {

            app.backgroundThreadShortToast("你还有数据没有填写");
        }
    }

    private void save_data_last() {
        String desc = mQuestionDesc.getText().toString();
        String a = mQuestionA.getText().toString();
        String b = mQuestionB.getText().toString();
        String c = mQuestionC.getText().toString();
        String d = mQuestionD.getText().toString();
        String answerParse = mQuestionAnswerParse.getText().toString();

        if (NullUtils.isNotNull(new String[]{desc, a, b, c, d, answer}, ALTER_NULL_INFO)) {


            all_data.append(curPage, new Question(desc, a, b, c, d, answer, answerParse));


        } else {

            app.backgroundThreadShortToast("你还有数据没有填写");
        }
    }

    private void setQuestData(Question question) {
        mQuestionA.setText(question.getOp_a());
        mQuestionB.setText(question.getOp_b());
        mQuestionC.setText(question.getOp_c());
        mQuestionD.setText(question.getOp_d());
        mQuestionDesc.setText(question.getDesc());
        mQuestionAnswerParse.setText(question.getAnswer_parse());
        setAnswer(question.getAnwser());


    }

    private void addquestion() {
        String desc = mQuestionDesc.getText().toString();
        String a = mQuestionA.getText().toString();
        String b = mQuestionB.getText().toString();
        String c = mQuestionC.getText().toString();
        String d = mQuestionD.getText().toString();

        //这里判断数据不为空
        if (NullUtils.isNotNull(new String[]{desc, a, b, c, d, answer}, ALTER_NULL_INFO)) {
            //把当前页面的内容写入
            all_data.append(curPage, new Question(desc, a, b, c, d, answer, ""));

            curPage++;
            //设置下面的内容
            if (curPage <= all_data.size() - 1) {
                setQuestData(all_data.get(curPage));
            } else {
                setNullData();
            }

        }

    }

    private void setNullData() {
        mQuestionA.setText("");
        mQuestionB.setText("");
        mQuestionC.setText("");
        mQuestionD.setText("");
        mQuestionDesc.setText("");
        mQuestionAnswerParse.setText("");


    }

    private void setAnswer(String answer) {

        switch (answer) {
            case "A":
                mCheckA.setChecked(true);
                break;
            case "B":
                mCheckB.setChecked(true);
                break;
            case "C":
                mCheckC.setChecked(true);
                break;
            case "D":
                mCheckD.setChecked(true);
                break;

        }
    }


    private void initView() {
        mQuestionDesc = (EditText) findViewById(R.id.question_desc);
        mQuestionA = (EditText) findViewById(R.id.question_a);
        mQuestionB = (EditText) findViewById(R.id.question_b);
        mQuestionC = (EditText) findViewById(R.id.question_c);
        mQuestionD = (EditText) findViewById(R.id.question_d);
        mQuestionBackToFront = (Button) findViewById(R.id.question_back_to_front);
        mQuestionBackToFront.setOnClickListener(this);
        mQuestionToNext = (Button) findViewById(R.id.question_to_next);
        mQuestionToNext.setOnClickListener(this);
        mPostData = (Button) findViewById(R.id.post_data);
        mPostData.setOnClickListener(this);
        mCheckA = (RadioButton) findViewById(R.id.check_a);
        mCheckB = (RadioButton) findViewById(R.id.check_b);
        mCheckC = (RadioButton) findViewById(R.id.check_c);
        mCheckD = (RadioButton) findViewById(R.id.check_d);
        mQuestionAnswerGroup = (RadioGroup) findViewById(R.id.question_answer_group);
        mQuestionAnswerGroup.setOnClickListener(this);
        mQuestionAnswerParse = (EditText) findViewById(R.id.question_answer_parse);

        mQuestionAnswerGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

                switch (checkedId) {
                    case R.id.check_a:
                        answer = "A";
                        break;
                    case R.id.check_b:
                        answer = "B";
                        break;
                    case R.id.check_c:
                        answer = "C";
                        break;
                    case R.id.check_d:
                        answer = "D";
                        break;

                }

            }
        });

    }


}
